<template>
    <!-- 标签栏 -->
    <van-tabs v-model:active="StatusActive" sticky @click-tab="TabChange">
        <van-tab v-for="(item, key) in StatusList" :title="item.title" :name="item.value" :key="key"></van-tab>
    </van-tabs>

    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="refresh">
        <!-- 加载列表 -->
        <van-list v-model:loading="loading" :finished="finished" :offset="10" 
            finished-text="没有更多了" @load="load">
            <!-- 商品卡片 -->
            <van-card v-for="item in list" :key="item.id" :title="item.proname" :thumb="item.product_thumb" :num="item.pronum" :tag="item.status_text" @click-thumb="ProductList(item.prolist)">
                <template #title>
                    <div class="title">订单号：{{item.code}}</div>
                </template>

                <!-- 卡片的插槽部分 -->
                <template #desc v-if="item.attrs">
                    <van-tag v-for="(tag, index) in item.attrs" :key="index" class="tag" type="danger">{{tag.value}}</van-tag>
                </template>

                <template #desc v-else>
                    <van-tag class="tag" type="danger">无规格数据</van-tag>
                </template>

                <template #tags>
                    <div class="price">下单时间：{{item.createtime_text}}</div>
                </template>

                <template #price>
                    <div class="price">订单总价：￥{{item.amount}}</div>
                </template>

                <template #footer>
                    <!-- status = 1 仅退款 -->
                    <van-button v-if="item.status == '1'" class="button" type="danger" size="small" @click="Refund1(item.id)">申请退款</van-button>
                    <van-button v-if="item.status == '2'" class="button" type="danger" size="small" @click="Refund2(item.id)">申请退货退款</van-button>

                    <!-- status = 2 -->
                    <van-button v-if="item.status == '2'" class="button" type="success" size="small" @click="ConfirmReceive(item.id)">确认收货</van-button>
                    <van-button v-if="item.status == '2'" class="button" type="warning" size="small" @click="ToExpress(item.id)">物流详情</van-button>

                    <!-- status = 3 已收货 -->
                    <van-button v-if="item.status == '3'" class="button" type="warning" size="small" @click="OrderInfo(item.id)">立即评价</van-button>

                    <van-button v-if="item.status == '-2'" class="button" type="success" size="small">等待后台审核...</van-button>

                    <van-button v-if="item.status == '-3'" class="button" type="warning" size="small" @click="BackInfo(item)">请填写退货信息</van-button>

                    <van-button class="button" type="primary" size="small" @click="OrderInfo(item.id)">订单详情</van-button>
                </template>
            </van-card>
        </van-list>
    </van-pull-refresh>

    <!-- 仅退款弹框 -->
    <van-popup v-model:show="ApplyShow1" position="bottom" round :style="{paddingBottom: '20px'}">
        <van-picker
            title="退款原因"
            :columns="RemarkList"
            @cancel="ApplyShow1 = false"
            @confirm="RefundApply"
        />
    </van-popup>

    <!-- 退货退款的弹框 -->
    <van-popup v-model:show="ApplyShow2" position="bottom" round>
        <van-form @submit="OrderApplyConfirm">
            <van-field v-model="remark" name="remark" rows="5" autosize type="textarea" maxlength="120"
                placeholder="请输入申请原因" show-word-limit :rules="[{ required: true, message: '请填写申请原因' }]" />
            <van-button square block color="linear-gradient(160deg, #0093E9 0%, #80D0C7 100%)"
                native-type="submit">提交申请</van-button>
        </van-form>
    </van-popup>

    <!-- 商品列表弹出框 -->
    <van-popup 
        v-model:show="ProShow" 
        position="bottom" 
        round
        style="padding: 10% 0%;"
    >
        <van-card v-for="item in prolist" :thumb="item.products.thumb_text" :num="item.pronum">
            <template #title>
                <div class="title">{{item.products.name}}</div>
            </template>
    
            <!-- 卡片的插槽部分 -->
            <template #desc v-if="item.attrs">
                <van-tag v-for="(attr, index) in item.attrs" :key="index" class="tag" type="primary">{{attr.value}}</van-tag>
            </template>
            <template #desc v-else>
                <van-tag class="tag" type="danger">无规格数据</van-tag>
            </template>
    
            <template #tags>
                <div class="price">单价：￥{{item.price}}</div>
            </template>
    
            <template #price>
                <div class="price">合计：￥{{item.total}}</div>
            </template>
        </van-card>

        <div style="width:50%;margin:2em auto 0em;">
            <van-button round block type="primary" @click="ProShow = false">关闭</van-button>
        </div>
    </van-popup>

    <!-- 退货表单信息的弹出框 -->
    <van-popup v-model:show="BackShow" position="bottom" round :style="{height: '40em'}">
        <h4 style="padding:0.5em 1em;">返厂退货信息</h4>

        <van-form>
            <van-field
                label="联系人"
                v-model="factory.contact"
                readonly
            />
            <van-field
                label="手机号"
                v-model="factory.mobile"
                readonly
            />
            <van-field
                label="返厂地址"
                v-model="factory.address"
                readonly
            />
        </van-form>

        <van-divider
        :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"
        >分割线</van-divider>

        <van-form @submit="BackSubmit">
            <van-field
                label="物流公司"
                v-model="back.express"
                name="express"
                placeholder="请选择物流公司"
                is-link
                readonly
                @click="ExpressShow = true"
            />

            <van-field
                label="快递单号"
                v-model="back.expresscode"
                name="expresscode"
                placeholder="请输入物流单号"
                :rules="[{required: true, message: '请输入物流单号'}]"
            />

            <van-field 
                label="退货理由"
                type="textarea"
                rows="3"
                v-model="back.remark"
                placeholder="请输入退货理由"
                :rules="[
                    {required: true, message: '请输入退货理由'},
                ]"
            />

            <van-field label="上传图集">
                <template #input>
                    <van-uploader 
                        v-model="thumbs" 
                        multiple 
                        :max-count="6"
                    />
                </template>
            </van-field>

            <div style="width:50%;margin:2em auto;">
                <van-button round block color="linear-gradient(160deg, #0093E9 0%, #80D0C7 100%)" native-type="submit">提交</van-button>
            </div>
        </van-form>

    </van-popup>

    <van-popup v-model:show="ExpressShow" position="bottom" round>
        <van-picker 
            :columns-field-names="{text: 'name', value: 'name'}"
            :columns="express"
            v-model="ExpressActive"
            title="物流公司"
            @confirm="ExpressConfirm"
            @cancel="ExpressShow = false"
        />
    </van-popup>
</template>

<script setup>
    const { proxy } = getCurrentInstance()

    let business = proxy.$business

    //标签栏数据
    let StatusActive = ref('0')
    let StatusList = ref([
        { title: '全部', value: '0' },
        { title: '已支付', value: '1' },
        { title: '已发货', value: '2' },
        { title: '已收货', value: '3' },
        { title: '已完成', value: '4' },
        { title: '退货退款', value: '-1' },
    ])

    //下拉刷新的数据
    let list = ref([]) //数据列表
    let page = ref(1)  //分页
    let loading = ref(false) //加载状态
    let finished = ref(false) //是否无更多数据
    let refreshing = ref(false) //下拉刷新

    
    let prolist = ref([]) //订单下的商品列表
    let ProShow = ref(false)

    // 申请仅退款
    let orderid = ref(0)
    let ApplyShow1 = ref(false)
    let RemarkList = ref([
        {text: '拍错了', value: '拍错了'},
        {text: '地址有误', value: '地址有误'},
        {text: '不想要了', value: '不想要了'},
        {text: '参数选错了', value: '参数选错了'},
        {text: '选择其他的', value: '选择其他的'},
    ])

    // 退货退款 
    let ApplyShow2 = ref(false)
    let remark = ref('')

    //退货填写表单
    let order = ref({})
    let BackShow = ref(false)
    let back = ref({expressid: 0, express: '', remark: ''})
    let factory = ref({})
    let express = ref([])
    let thumbs = ref([])
    let ExpressShow = ref(false)
    let ExpressActive = ref([0])


    // 标签栏切换
    const TabChange = async ({ name }) => {
        StatusActive.value = name
        refresh()
    }

    //下拉刷新
    const refresh = async () => {
        //清空查询参数
        page.value = 1
        list.value = []
        finished.value = false
        loading.value = true;
        refreshing.value = true;

        // 可以去掉定时器
        setTimeout(load, 500);
    }

    //加载数据方法 查询订单数据
    const load = async () => 
    {
        //判断是否为加载中的状态
        if (refreshing.value) 
        {
            refreshing.value = false
        }

        //组装数据
        var params = {
            busid: business.value.id,
            page: page.value,
            status: StatusActive.value
        }
        // console.log(params)
        // return false

        var result = await proxy.$POST({url: '/order/index', params})

        // console.log(result)
        // return false

        //请求发送完毕后，加载状态也就完毕了
        loading.value = false

        if(result.code == 0)
        {
            // 如果没有更多数据了 就说明已经加载到底了....
            finished.value = true;

            proxy.$fail(result.msg);

            return false
        }

        let count = result.data ? result.data.count : 0;
        list.value = result.data ? list.value.concat(result.data.list) : [];

        if(list.value.length >= count)
        {
            finished.value = true
            return false
        }
        
        page.value = page.value + 1
    }

    //点击商品图片
    const ProductList = (items) =>
    {
        items.map(value => value.attrs = JSON.parse(value.attrs))

        prolist.value = items

        ProShow.value = true
    }

    //确认收货
    const ConfirmReceive = async (orderid) =>
    {
        proxy.$confirm({
            title: '确认收货提醒',
            message: '是否确认收货',
        }).then(async () => {
            var result = await proxy.$POST({url: '/order/receive', params: {orderid}})

            if(result.code == 0)
            {
                proxy.$fail(result.msg)
                return false
            }

            proxy.$success(result.msg)

            refresh()

        }).catch(err => {})
    }

    //跳转订单详情
    const OrderInfo = (orderid) => proxy.$router.push({path: '/order/info', query: {orderid}})

    //跳转物流界面
    const ToExpress = (orderid) => proxy.$router.push({path: '/order/express', query: {orderid}})

    //申请退款
    const Refund1 = async (id) =>
    {
        proxy.$confirm({
            title: '退款提醒',
            message: '是否确认申请退款'
        }).then(async () => {
            ApplyShow1.value = true
            orderid.value = id
        }).catch(err => {})
    }

    //申请仅退款
    const RefundApply = async ({selectedValues}) =>
    {
        // 退款的原因
        var refundreason = selectedValues[0] ?? '拍错了'

        // 组装数据
        var params = {
            orderid: orderid.value,
            refundreason
        }

        //发起请求
        var result = await proxy.$POST({url: '/order/refund', params})

        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false
        }

        //关闭弹框
        ApplyShow1.value = false

        proxy.$success(result.msg)

        refresh() //重新刷新列表
    }

    // 申请退货退款
    const Refund2 = async (id) =>
    {
        proxy.$confirm({
            title: '退款提醒',
            message: '是否确认申请退货退款'
        }).then(async () => {
            ApplyShow2.value = true
            orderid.value = id
        }).catch(err => {})
    }

    //提交退货退款的原因
    const OrderApplyConfirm = async () =>
    {
        ApplyShow2.value = false

        //组装数据
        var params = {
            orderid:orderid.value,
            refundreason: remark.value
        }

        var result = await proxy.$POST({url: '/order/back', params})

        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false;
        }

        proxy.$success(result.msg)

        refresh() //重新刷新列表
    }

    //填写退货订单
    const BackInfo = async (item) =>
    {
        BackShow.value = true

        //保留订单信息
        order.value = item
        
        //获取退货返厂的信息
        var result = await proxy.$GET({url: '/order/factory'})

        factory.value = result.data.factory
        express.value = result.data.express
    }

    // selectedOptions 选中项的信息
    const ExpressConfirm = ({selectedOptions}) =>
    {
        ExpressShow.value = false

        back.value.expressid = selectedOptions[0].id
        back.value.express = selectedOptions[0].name
    }

    //提交退货信息
    const BackSubmit = async (values) =>
    {
        //组装信息
        var params = {
            orderid: order.value.id,
            ordercode: order.value.code, //订单号码
            busid: order.value.busid,
            expressid: back.value.expressid, //物流公司的外键
            expresscode: back.value.expresscode, //物流单号
            remark:back.value.remark,
        }

         //判断图片的个数
         if(thumbs.value.length > 0)
        {
            var list = []

            //图片追加到数组中
            thumbs.value.map(item => (item.file && list.push(item.file)))
            params.thumbs = list
        }

        if(params.thumbs)
        {
            //多图上传
            var result = await proxy.$UPLOADS({url: '/order/factory', params})
        }else
        {
            //POST方式提交
            var result = await proxy.$POST({url: '/order/factory', params})
        }

        BackShow.value = false
    }



</script>


<style scoped>
    @import url('/assets/css/OrderIndex.css');
</style>